#include "terraview.h"
#include "terramodel.h"
#include "../external/transformable/transformable.h"
#include <QPainter>
#include <QPixmap>
#include <QDebug>

std::shared_ptr<TerraView> terra_view = nullptr;

// 异步图层
TerraView::TerraView() : AsyncLayer(1) {}

void TerraView::draw(QPixmap &pixmap)
{
    QPainter painter(&pixmap);

    // 计算当前屏幕显示范围
    double x_min, x_max, y_min, y_max;
    TRANS->pixelToMap(0, TRANS->height(), x_min, y_min);
    TRANS->pixelToMap(TRANS->width(), 0, x_max, y_max);

    // 获取范围内的瓦片
    std::vector<TerraModel::Tile> tiles;
    terra_model->toVector(tiles, x_min, x_max, y_min, y_max);

    // 转像素坐标
    std::vector<TerraModel::Tile> pixels(tiles.size());
    for (size_t i = 0; i < tiles.size(); ++i)
    {
        TerraModel::Tile pixel;
        TRANS->mapToPixel(tiles[i].x, tiles[i].y, pixel.x, pixel.y);
        pixel.id = tiles[i].id;

        pixels.emplace_back(pixel);
    }

    // 按照材料分类绘制 QVector -> QMap<QColor, QVector>
    QMap<unsigned, QVector<TerraModel::Tile> > classes_by_material;
    for (size_t i = 0; i < pixels.size(); ++i)
    {
        classes_by_material[pixels[i].id].emplace_back(pixels[i]);
    }

    // 获取瓦片单元像素边长
    double pixel_len;
    TRANS->mapLenInPixel(terra_model->_resolution, pixel_len);
    pixel_len = pixel_len * 0.8; // 留空隙
    pixel_len = (pixel_len < 1) ? 1 : pixel_len; // 防止消失

    // 绘制瓦片集合
    painter.setPen(Qt::NoPen);
    for (auto it = classes_by_material.cbegin(); it != classes_by_material.cend(); ++it)
    {
        auto material = terra_model->_material_table[it.key()];
        painter.setBrush(material.color);

        for (qsizetype i = 0; i < it.value().size(); ++i)
        {
            painter.drawRect(it.value()[i].x, it.value()[i].y, pixel_len, pixel_len);
        }
    }
}
